package com.how.config;

import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.NoneShardingStrategyConfiguration;

import java.util.LinkedList;
import java.util.List;

public class BaseTableRuleConfig {

    static final String DATABASE = "base";

    public static List<TableRuleConfiguration> getTableRuleConfigurations() {
        List<TableRuleConfiguration> tableRuleConfigs = new LinkedList<>();

        String actualDataNodes = DATABASE + ".".concat("base_user").concat("$->{0..1}");
        TableRuleConfiguration ruleConfiguration = new TableRuleConfiguration("base_user", actualDataNodes);
        String algorithmExpression = "base_user".concat("$->{id % 2}");
        // 表策略
        ruleConfiguration.setTableShardingStrategyConfig(
                new InlineShardingStrategyConfiguration("id", algorithmExpression));
        // 分库策略
//        ruleConfiguration.setDatabaseShardingStrategyConfig(
//                new InlineShardingStrategyConfiguration("id", DATABASE + "$->{id % 2}"));
        ruleConfiguration.setDatabaseShardingStrategyConfig(new NoneShardingStrategyConfiguration());

        // 指定表的主键生成策略为SNOWFLAKE
        ruleConfiguration.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "id"));

        tableRuleConfigs.add(ruleConfiguration);

        return tableRuleConfigs;
    }
}